package com.example.controller;

import com.example.util.VerifyCodeUtils;
import com.example.entity.User;
import com.example.service.UserService;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;


   @GetMapping("/register")
   public String register(){
       return "/home/register";
   }
    @PostMapping("/register")
    public String register(@Param("username") String username,
                           @Param("password") String password,
                           @Param("email") String email,
                           @Param("phone") String phone,
                           @Param("role") int role,
                           Model model) {
        System.out.println("username"+username);
       int id=userService.addUser(username,password,email,phone,role);
        System.out.println(id);
        return "/home/Login";
    }

    @RequestMapping("login")
    public ModelAndView Login(
            @RequestParam("verifyCode") String verifyCode,
            @RequestParam String loginUserName,
            @RequestParam String loginPassword,
            HttpSession session) {

        ModelAndView mv = new ModelAndView();

        // 1. 先校验验证码
        String sessionVerifyCode = (String) session.getAttribute("verifycode");
        if (sessionVerifyCode == null || !sessionVerifyCode.equalsIgnoreCase(verifyCode)) {
            mv.addObject("errorMsg", "验证码错误！");
            mv.setViewName("/home/Login"); // 返回登录页
            return mv;
        }

        // 2. 验证码正确，再校验用户
        User user = this.userService.getUserByUserNameAndPassword(loginUserName, loginPassword);
        if (user == null) {
            mv.addObject("errorMsg", "用户名或密码错误！");
            mv.setViewName("/home/Login");
            return mv;
        }

        // 3. 根据角色跳转不同页面
        int role = userService.getUserRole(user.getUser_id());
        if (role == 0) {
            session.setAttribute("admin_user", user);
            mv.setViewName("/home/admin");
        } else {
            session.setAttribute("login_user", user);
            mv.setViewName("/home/top");
        }

        return mv;
    }
    @GetMapping("/list")
    public String userList(Model model){
        List<User> userList = userService.userList();
        System.out.println("userList"+userList);
        model.addAttribute("userList",userList);
        return "/user/userList";
    }
    @GetMapping("/delete")
    public String deleteUser(@Param("user_id") Integer user_id){
        userService.deleteUser(user_id);
        System.out.println("delete_user_id"+user_id);
        return "redirect:/user/list";
    }
    @GetMapping("/edit/{user_id}")
    public String toEditPage(@PathVariable("user_id") Integer user_id, Model model) {
        User user = userService.getUserById(user_id);
        model.addAttribute("user", user);
        return "user/edit";
    }

    @GetMapping("/edit")
    public String edit(User user) {
        userService.updateUser(user);
        return "redirect:/user/list";
    }
    @GetMapping("/add")
    public String toAddPage() {
        return "user/add";
    }

    @PostMapping("/add")
    public String add(User user) {
        userService.addUser(user);
        return "redirect:/user/list";
    }
    @GetMapping("/profile")
    public String showProfile(Model model, HttpSession session) {
        User currentUser = (User) session.getAttribute("login_user");
        if (currentUser == null) {
            currentUser = (User) session.getAttribute("admin_user");
        }

        if (currentUser == null) {
            return "redirect:/home/newLogin";
        }

        User user = userService.getUserById(currentUser.getUser_id());
        model.addAttribute("user", user);
        return "/user/profile";
    }
    @PostMapping("/updateProfile")
    public String updateProfile(@RequestParam(required = false) String email,
                                @RequestParam(required = false) String phone,
                                HttpSession session, RedirectAttributes redirectAttributes){
        if (email == null && phone == null) {
            redirectAttributes.addFlashAttribute("error", "请提供要更新的信息");
            return "redirect:/user/profile";
        }

        User currentUser = (User) session.getAttribute("login_user");
        if (currentUser == null) {
            currentUser = (User) session.getAttribute("admin_user");
        }

        if (currentUser == null) {
            return "redirect:/home/newLogin";
        }
        User user = userService.getUserById(currentUser.getUser_id());

        // 只更新非空的字段
        if (email != null) {
            user.setEmail(email);
        }
        if (phone != null) {
            user.setPhone(phone);
        }

        boolean updated = userService.updateUser(user);
        if (updated) {
            // 更新session中的用户信息
            if (session.getAttribute("login_user") != null) {
                session.setAttribute("login_user", user);
            } else if (session.getAttribute("admin_user") != null) {
                session.setAttribute("admin_user", user);
            }
            redirectAttributes.addFlashAttribute("success", true);
        } else {
            redirectAttributes.addFlashAttribute("error", "更新个人信息失败");
        }

        return "redirect:/user/profile";
    }
    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();  // 使session失效
        }
        return "/home/Login";  // 重定向到登录页
    }
    @GetMapping("/verifyCode")
    public void generateVerifyCode(HttpSession session, HttpServletResponse response) throws IOException {
        //  生成随机字符串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        System.out.println(verifyCode);
        // 保存随机字符串到session
        session.setAttribute("verifycode", verifyCode);
        // 将随机字符串生成图片
        response.setContentType("images/png");
        // 指定响应类型为图片
        try (OutputStream outputStream = response.getOutputStream()) {
            VerifyCodeUtils.outputImage(220, 60, outputStream, verifyCode);
        }
    }
}

